import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { authAPI } from '../services/api';
import './Login.css';

const Login = ({ onLogin }) => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useEffect(() => {
    // 检查是否已经登录
    const token = localStorage.getItem('token');
    const user = localStorage.getItem('user');
    console.log('Checking existing auth:', {
      hasToken: !!token,
      hasUser: !!user
    });
    
    if (token && user) {
      console.log('Found existing auth data, redirecting to ranking');
      navigate('/ranking');
    }
  }, [navigate]);

  const handleSubmit = async (values) => {
    console.log('Form submitted with values:', {
      username: values.username,
      passwordLength: values.password?.length
    });
    
    setLoading(true);
    try {
      console.log('Attempting login...');
      const success = await onLogin(values);
      console.log('Login attempt result:', { success });
      
      if (success) {
        // 验证登录状态
        const token = localStorage.getItem('token');
        const user = localStorage.getItem('user');
        console.log('Verifying login success:', {
          hasToken: !!token,
          hasUser: !!user
        });
        
        message.success('登录成功');
        console.log('Navigating to ranking page');
        navigate('/ranking');
      } else {
        console.log('Login failed');
        message.error('登录失败，请检查用户名和密码');
      }
    } catch (err) {
      console.error('Login error:', {
        message: err.message,
        response: {
          status: err.response?.status,
          data: err.response?.data
        }
      });
      message.error('登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <Card className="login-card" title="用户登录">
        <Form
          form={form}
          name="login"
          onFinish={handleSubmit}
          layout="vertical"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>

          <div className="register-link">
            还没有账号？<Link to="/register">立即注册</Link>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default Login; 